package monster.com.cvh.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tencent.tinker.loader.app.TinkerApplication;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;
import monster.com.cvh.R;
import monster.com.cvh.activity.LoginActivity;
import monster.com.cvh.activity.NewsDetailsActivity;
import monster.com.cvh.adapter.NewsAdapter;
import monster.com.cvh.application.TinkerApplicationLike;
import monster.com.cvh.bean.MessageEvent;
import monster.com.cvh.bean.NewsBean;
import monster.com.cvh.bean.SlideShowBean;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.NetworkUtil;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.WrapContentLinearLayoutManager;
import okhttp3.Call;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by ASUS on 2018/3/2.
 */

public class NewsFragment extends PermissionFragment {
    private static final int ARTICLE_CODE = 13801;
    private static final String TAG = "lixiaofei";
    @BindView(R.id.recyclerview_fragment_news)
    RecyclerView recyclerviewFragmentNews;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private List<NewsBean.DataBean> mDatas = new ArrayList<>();
    private View view;
    private View newsHeadView;
    private Banner bannerFragmentNews;
    private ArrayList<String> mImgUrl;
    private Gson gson;
    private SlideShowBean slideShowBean;
    private int mType;
    private int page = 0;
    private NewsAdapter adapter;
    private List<NewsBean.DataBean> data;
    private boolean collection;
    private String token = null;
    private boolean is_collect;
    private View emptyView;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments().getInt("type");
        newsHeadView = LayoutInflater.from(getActivity()).inflate(R.layout.item_banner, null);
        Log.i("lixiaofei", "onCreate: " + mType);
        token = SPUtils.getString(getActivity(), "token", "");
        startNews();
    }

    @Override
    public void onStart() {
        super.onStart();
        checkNetWork();
    }

    /**
     * 获取数据
     */
    private void startNews() {
        //判断是否为游客
        if (token.isEmpty() || token.equals("")) {
            Log.i(TAG, "onCreate: " + "我是游客");
            switch (mType) {
                case 1:
                    if (mDatas.size() == 0) {
                        getTouristNews(0, "攻略");
                    }

                    break;
                case 2:
                    if (mDatas.size() == 0) {
                        getTouristNews(0, "干货");
                    }

                    break;
                case 3:
                    if (mDatas.size() == 0) {
                        getTouristNews(0, "活动");
                    }
                    break;
            }
        } else {
            switch (mType) {
                case 1:
                    if (mDatas.size() == 0) {
                        getNews(0, "攻略");
                    }

                    break;
                case 2:
                    if (mDatas.size() == 0) {
                        getNews(0, "干货");
                    }

                    break;
                case 3:
                    if (mDatas.size() == 0) {
                        getNews(0, "活动");
                    }
                    break;
            }
        }

    }

    /**
     * 弹出网络设置
     *
     * @param context 上下文
     */
    public void showSetNetworkUI(final Context context) {
        // 提示对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示")
                .setMessage("网络连接不可用,是否进行设置?")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Intent intent = null;
                        // 判断手机系统的版本 即API大于10 就是3.0或以上版本
                        if (Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    Settings.ACTION_WIFI_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 检查网络
     */
    private void checkNetWork() {
        if (!NetworkUtil.isNetworkAvailable(getActivity())) {
            showSetNetworkUI(getActivity());
            ImageView iv = emptyView.findViewById(R.id.iv_empty);
            iv.setBackgroundResource(R.mipmap.mine_read_nothing);
            TextView tv = emptyView.findViewById(R.id.tv_empty);
            tv.setText("暂无网络，请联网....");
            adapter.setEmptyView(emptyView);
        } else {
//            Log.e("lixiaofei", "onStart: " + "网络可用");
        }
    }

    /**
     * 获取新闻列表
     *
     * @param pageNum 翻页的页数
     */
    private void getNews(final int pageNum, final String type) {
        OkGo.<String>get(MyConstant.NEWSLIST).params("type", type).params("token", SPUtils.getString(getActivity(), "token", ""))
                .params("page_index", pageNum).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    final NewsBean newsBean = gson.fromJson(s, NewsBean.class);
                    switch (newsBean.getCode()) {
                        case 1:
                            data = newsBean.getData();
                            Log.i("lixiaofei", "onSuccess: " + data.size() + "pageNum :" + pageNum);
                            if (null != data && data.size() > 0) {
                                adapter.addData(data);
                                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        int id = mDatas.get(position).getId();
                                        Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                                        is_collect = mDatas.get(position).isIs_collect();
                                        intent.putExtra("id", id);
                                        intent.putExtra("postion", position);
                                        intent.putExtra("isCollect", is_collect);
                                        intent.putExtra("reply", mDatas.get(position).getComment_count());
                                        startActivityForResult(intent, ARTICLE_CODE);
                                    }
                                });
                            } else {
                                showToastShort("已无更多数据");
                            }
                            break;
                        case -1002:
                        case -1003:
                        case -1004:
                            showToastLong("登录已经过期，请退出重新登录");
                            goLogin();
                            break;
                    }
                } catch (Exception e) {
                    showToastLong("获取失败，请稍后重试");
                    return;

                }


            }
        });
    }

    private void goLogin() {
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }


    /**
     * 游客模式获取新闻列表
     */

    /**
     * 获取新闻列表
     *
     * @param pageNum 翻页的页数
     */
    private void getTouristNews(final int pageNum, final String type) {
        OkGo.<String>get(MyConstant.NEWSLIST).params("type", type).params("page_index", pageNum).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    final NewsBean newsBean = gson.fromJson(s, NewsBean.class);
                    switch (newsBean.getCode()) {
                        case 1:
                            data = newsBean.getData();
                            Log.i("lixiaofei", "onSuccess: " + data.size() + "pageNum :" + pageNum);
                            if (null != data && data.size() > 0) {
                                adapter.addData(data);

                            } else {
                                showToastLong("已无更多数据");
                            }
                    }
                } catch (Exception e) {
                    showToastLong("获取失败，请稍后重试");
                    return;
                }

            }
        });
    }

    private void initBanner() {
        bannerFragmentNews = newsHeadView.findViewById(R.id.banner_fragment_news);
        bannerFragmentNews.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器，图片加载器在下方
        bannerFragmentNews.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        bannerFragmentNews.setImages(mImgUrl);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        bannerFragmentNews.setBannerAnimation(Transformer.Default);
        //设置轮播间隔时间
        bannerFragmentNews.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        bannerFragmentNews.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        bannerFragmentNews.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                //必须最后调用的方法，启动轮播图。
                .start();

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initData() {
        emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.item_empty, null);
        EventBus.getDefault().register(this);
        Log.i("lixiaofei", "onViewCreated: " + mType);
        mImgUrl = new ArrayList<>(4);
        gson = new Gson();
//        if (isFirstIn) {
//            mRefreshLayout.autoRefresh();
//        }
        recyclerviewFragmentNews.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
//        recyclerviewFragmentNews.addItemDecoration(new RecyclerViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, 2, Color.parseColor("#cfcfcf")));
        adapter = new NewsAdapter(R.layout.item_news, mDatas);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int id = mDatas.get(position).getId();
                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("isCollect", mDatas.get(position).isIs_collect());
                intent.putExtra("reply", mDatas.get(position).getComment_count());
                startActivityForResult(intent, ARTICLE_CODE);
            }
        });
        switch (mType) {
            case 1:
                getBannerFromService("攻略");
                break;
            case 2:
                getBannerFromService("干货");
                break;
            case 3:
                getBannerFromService("活动");
                break;
        }
        adapter.addHeaderView(newsHeadView);
        recyclerviewFragmentNews.setAdapter(adapter);
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (token == null || token.equals("")) {
                    touristRefreshlayout(refreshlayout, false, mType);
                } else {
                    refreshlayout(refreshlayout, false, mType);
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (token == null || token.equals("")) {
                    touristRefreshlayout(refreshlayout, true, mType);
                } else {
                    refreshlayout(refreshlayout, true, mType);
                }
            }
        });

    }

    /**
     * 销毁EventBus
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 接收事件
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        Log.i(TAG, "Event: " + messageEvent.getMessage());
        mRefreshLayout.autoRefresh();
    }

    /**
     * 获取游客的news
     *
     * @param refreshlayout
     * @param b
     * @param mType
     */
    private void touristRefreshlayout(RefreshLayout refreshlayout, final boolean b, final int mType) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (b) {
                    Log.i("lixiaofei", "run: " + "下拉刷新了" + mType);
                    if (mType == 1) {
                        Log.i("lixiaofei", "run: " + "我是攻略");
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取攻略的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("攻略");
                            getTouristNews(page, "攻略");
                        } else {
                            getTouristNews(page, "攻略");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();
                        page = 1;
                    } else if (mType == 2) {
                        Log.i("lixiaofei", "run: " + "我是干货");
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取干货的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("干货");
                            getTouristNews(page, "干货");
                        } else {
                            getTouristNews(page, "干货");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();
                        page = 1;
                    } else if (mType == 3) {
                        Log.i("lixiaofei", "run: " + "我是活动");
                        //活动的Fragment
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取活动的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("活动");
                            getTouristNews(page, "活动");
                        } else {
                            getTouristNews(page, "活动");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();
                        page = 1;

                    }
//                    isFirstIn = false;
                } else {
                    page++;
                    Log.i("lixiaofei", "run: " + "加载更多了" + mType);
                    if (mType == 1) {
                        getTouristNews(page, "攻略");
                    } else if (mType == 2) {
                        getTouristNews(page, "干货");
                    } else if (mType == 3) {
                        getTouristNews(page, "活动");
                    }
                    mRefreshLayout.finishLoadmore();
                }


            }
        }, 100);
    }

    private void refreshlayout(RefreshLayout refreshlayout, final boolean b, final int mType) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (b) {
                    Log.i("lixiaofei", "run: " + "下拉刷新了" + mType);
                    if (mType == 1) {
                        Log.i("lixiaofei", "run: " + "我是攻略");
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取攻略的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("攻略");
                            getNews(page, "攻略");
                        } else {
                            getNews(page, "攻略");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();
//                        page = 1;
                    } else if (mType == 2) {
                        Log.i("lixiaofei", "run: " + "我是干货");
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取干货的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("干货");
                            getNews(page, "干货");
                        } else {
                            getNews(page, "干货");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();
//                        page = 1;
                    } else if (mType == 3) {
                        Log.i("lixiaofei", "run: " + "我是活动");
                        //活动的Fragment
                        if (mDatas.size() > 0) {
                            mDatas.clear();
                            page = 0;
                        }
                        //获取活动的banner
                        if (mImgUrl.size() == 0) {
                            getBannerFromService("活动");
                            getNews(page, "活动");
                        } else {
                            getNews(page, "活动");
                        }

                        recyclerviewFragmentNews.setAdapter(adapter);
                        mRefreshLayout.finishRefresh();


                    }
//                    isFirstIn = false;
                } else {
                    page++;
                    Log.i("lixiaofei", "run: " + "加载更多了" + mType);
                    if (mType == 1) {
                        getNews(page, "攻略");
                    } else if (mType == 2) {
                        getNews(page, "干货");
                    } else if (mType == 3) {
                        getNews(page, "活动");
                    }
                    mRefreshLayout.finishLoadmore();

                }


            }
        }, 2000);
    }

    /**
     * 获取轮播图
     *
     * @param type 类型
     */
    private void getBannerFromService(String type) {
        OkGo.<String>get(MyConstant.GETSLIDESHOW).params("type", type).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                slideShowBean = gson.fromJson(s, SlideShowBean.class);
                for (int i = 0; i < slideShowBean.getData().size(); i++) {
                    String cover_image_url = slideShowBean.getData().get(i).getCover_image_URL();
                    mImgUrl.add(cover_image_url);

                }
                initBanner();
                bannerFragmentNews.setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        Log.i("lixiaofei", "OnBannerClick: " + slideShowBean.getData().get(position).getArticle_id());
                        boolean is_collect = slideShowBean.getData().get(position).isIs_collect();
                        Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                        intent.putExtra("id", slideShowBean.getData().get(position).getArticle_id());
                        intent.putExtra("bannerPostion", position);
                        intent.putExtra("isCollect", is_collect);
                        intent.putExtra("reply", slideShowBean.getData().get(position).getComment_count());
                        startActivityForResult(intent, ARTICLE_CODE);
                    }
                });
            }

        });
    }

    @Override
    protected void initEvent() {

    }

    /**
     * 记录上个页面回调的收藏状态
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ARTICLE_CODE && resultCode == RESULT_OK) {
            collection = data.getBooleanExtra("article", false);
            int bannerPostion = data.getIntExtra("bannerPostion", -1);
            if (bannerPostion != -1) {
                slideShowBean.getData().get(bannerPostion).setIs_collect(collection);
            }

        }

    }

    //自定义的图片加载器
    public class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            if (context != null) {
                Glide.with(TinkerApplicationLike.getContext()).load(path).placeholder(R.mipmap.information_placeholderfigure).error(R.mipmap.information_placeholderfigure).into(imageView);
            } else {
                showToastLong("加载图片失败");
            }
        }
    }
}
